package jpopupmenu;

import javax.swing.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

/**
 * JPopupMenu 右键菜单，或上下文菜单
 * 1响应鼠标右键的点击
 * 2弹出菜单
 * - 创建JPopupMenu菜单
 * - 添加JMenuItem菜单项
 * - 弹出菜单窗口 popup.show(..)
 */
public class JPopupMenu01 {
    public static void main(String[] args) {
        JFrame jFrame = new JFrame("java-swing");
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jFrame.setSize(400,300);
        jFrame.setVisible(true);


        JPanel jPanel = new JPanel();
        jFrame.setContentPane(jPanel);
        JButton jButton = new JButton("DialogueBox");
        jPanel.add(jButton);


        jButton.addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON3){
                    showMenu(e);
                }
            }

            @Override
            public void mousePressed(MouseEvent e) {

            }

            @Override
            public void mouseReleased(MouseEvent e) {

            }

            @Override
            public void mouseEntered(MouseEvent e) {

            }

            @Override
            public void mouseExited(MouseEvent e) {

            }
        });


    }
    private static void showMenu(MouseEvent e){
        JPopupMenu menu = new JPopupMenu();
        JMenuItem item1 = new JMenuItem("另存为");
        menu.add(item1);

        menu.show(e.getComponent(),e.getX(),e.getY());
    }



}
